package com.tianji.promotion.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDate;

/**
 * @author Covey
 */
@Component
public class UserRemindDuplicateChecker {

    private static final String USER_REMIND_LOCK_KEY = "user:remind:lock:";

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 用户级别防重复：同一用户在同一天内只发送一次同类型提醒
     */
    public boolean tryLockUserRemind(Long userId, int hoursBefore) {
        String today = LocalDate.now().toString();
        String lockKey = USER_REMIND_LOCK_KEY + userId + ":" + hoursBefore + ":" + today;

        return Boolean.TRUE.equals(
                redisTemplate.opsForValue().setIfAbsent(lockKey, "1", Duration.ofHours(12))
        );
    }
}